<template>
  <div class="BuryList">
    <el-card>
      <div class="searchBox">
        <el-input placeholder="请输入内容" v-model="idInput">
          <template slot="prepend">事件名称</template>
        </el-input>
        <el-button class="btn" icon="el-icon-search" @click="buryingListBtn"
          >查询搜索</el-button
        >
        <el-button class="btn" icon="el-icon-download" @click="exportJson"
          >导出</el-button
        >
        <el-button class="btn" icon="el-icon-upload" @click="upJson"
          >导入</el-button
        >
        <el-button
          class="btn right"
          icon="el-icon-circle-plus-outline"
          @click="dialogFormVisible = true"
          >添加埋点</el-button
        >
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="event_name" label="事件名称"> </el-table-column>
        <el-table-column prop="create_time" label="时间"> </el-table-column>
        <el-table-column prop="event_id" label="事件ID"> </el-table-column>
        <el-table-column prop="os_id" label="系统ID"> </el-table-column>
        <el-table-column prop="app_id" label="应用ID"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getList"
      />
      <!-- 添加埋点弹框 -->
      <el-dialog
        title="添加埋点"
        :visible.sync="dialogFormVisible"
        width="30%"
        @close="addClose"
      >
        <el-form :model="form" :rules="rules" ref="ruleForm">
          <el-form-item
            label="事件名称"
            :label-width="formLabelWidth"
            prop="event_name"
          >
            <el-input v-model="form.event_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="事件ID"
            :label-width="formLabelWidth"
            prop="event_id"
          >
            <el-input v-model="form.event_id" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="应用ID" :label-width="formLabelWidth">
            <el-input
              v-model="form.app_id"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="系统ID"
            :label-width="formLabelWidth"
            prop="os_id"
          >
            <el-radio-group v-model="form.os_id">
              <el-radio label="android">android</el-radio>
              <el-radio label="ios">ios</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="buryingAdd">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑埋点弹框 -->
      <el-dialog
        title="编辑埋点"
        :visible.sync="dialogFormVisibleB"
        width="30%"
      >
        <el-form :model="formB" :rules="rules" ref="ruleFormB">
          <el-form-item label="ID" :label-width="formLabelWidth">
            <el-input v-model="formB.id" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item
            label="事件名称"
            :label-width="formLabelWidth"
            prop="event_name"
          >
            <el-input v-model="formB.event_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="事件ID"
            :label-width="formLabelWidth"
            prop="event_id"
          >
            <el-input v-model="formB.event_id" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="应用ID" :label-width="formLabelWidth">
            <el-input
              v-model="formB.app_id"
              disabled
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="系统ID"
            :label-width="formLabelWidth"
            prop="os_id"
          >
            <el-radio-group v-model="formB.os_id">
              <el-radio label="android">android</el-radio>
              <el-radio label="ios">ios</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="时间" :label-width="formLabelWidth">
            <el-input
              v-model="formB.create_time"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleB = false">取 消</el-button>
          <el-button type="primary" @click="editSaveBtn">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
    <el-dialog title="上传文件" :visible.sync="upDialogVisible" width="30%">
      <el-upload
        class="upload-demo"
        :http-request="upLoad"
        action
        :before-upload="beforeAvatarUpload"
        :multiple="false"
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <!-- <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div> -->
      </el-upload>
      <div class="tac">
        <el-button class="w300" size="small" type="primary" @click="upSubmit"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import {
  buryingList,
  buryingEdit,
  buryingAdd,
  BuryingImport,
} from "@/api/DataManagement";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
export default {
  components: { Pagination },
  inject: ["reload"],
  data() {
    return {
      idInput: "",
      tableData: [],
      total: 0,
      page: 1, //页码
      pageSize: 10, //每页条数
      //添加埋点弹框
      dialogFormVisible: false,
      form: {
        event_name: "", //事件名称
        event_id: "", //事件ID
        os_id: "", //系统ID
        app_id: "2a7efcc53a05ae31ea2d6bbe14ed2b94", //应用ID
      },
      formLabelWidth: "90px",
      //编辑埋点弹框
      formB: {
        id: "",
        event_name: "", //事件名称
        create_time: "", //时间
        event_id: "", //事件ID
        os_id: "", //系统ID
        app_id: "", //应用ID
      },
      dialogFormVisibleB: false,
      rules: {
        event_name: [
          { required: true, message: "请输入事件名称", trigger: "blur" },
        ],
        event_id: [
          { required: true, message: "请输入事件ID", trigger: "blur" },
        ],
        os_id: [{ required: true, message: "请选择系统ID", trigger: "change" }],
      },
      upDialogVisible: false,
      fileList: [],
      fileTxt: "",
      dataObj: {},
    };
  },
  methods: {
    //列表
    buryingList() {
      buryingList({
        page: this.page,
        pageSize: this.pageSize,
        id: "",
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = res.data.totalCount;
        }
      });
    },
    //查询
    buryingListBtn() {
      buryingList({
        page: this.page,
        pageSize: this.pageSize,
        id: this.idInput,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = res.data.totalCount;
        }
      });
    },
    //编辑打开弹框
    handleEdit(row) {
      this.dialogFormVisibleB = true;
      this.formB.id = row.id;
      this.formB.event_name = row.event_name; //事件名称
      this.formB.create_time = row.create_time; //时间
      this.formB.event_id = row.event_id; //事件ID
      this.formB.os_id = row.os_id; //系统ID
      this.formB.app_id = row.app_id; //应用ID
    },
    //编辑保存
    editSaveBtn() {
      this.$refs.ruleFormB.validate((valid) => {
        if (valid) {
          buryingEdit({
            id: this.formB.id,
            eventId: this.formB.event_id,
            eventName: this.formB.event_name,
            appId: this.formB.app_id,
            osId: this.formB.os_id,
          }).then((res) => {
            if (res.code == 0) {
              this.dialogFormVisibleB = false;
              this.$message({
                message: "编辑成功",
                type: "success",
              });
              this.reload();
            }
          });
        } else {
          return false;
        }
      });
    },
    //添加保存
    buryingAdd() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          buryingAdd({
            eventId: this.form.event_id, //事件ID
            eventName: this.form.event_name, //事件名称
            appId: this.form.app_id, //应用ID
            osId: this.form.os_id, //系统ID
          }).then((res) => {
            if (res.code == 0) {
              this.dialogFormVisible = false;
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.reload();
            }
          });
        } else {
          return false;
        }
      });
    },
    //分页
    getList() {
      buryingList({
        page: this.page,
        pageSize: this.pageSize,
        id: this.idInput,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = res.data.totalCount;
        }
      });
    },
    //关闭清理form
    addClose() {
      this.$refs.ruleForm.resetFields();
    },
    // exportExcel() {
    //   require.ensure([], () => {
    //     const { export_json_to_excel } = require("@/excel/Export2Excel"); //注意这个Export2Excel路径
    //     const tHeader = [
    //       "ID",
    //       "事件名称",
    //       "时间",
    //       "事件ID",
    //       "系统ID",
    //       "应用ID",
    //     ]; // 上面设置Excel的表格第一行的标题
    //     const filterVal = [
    //       "id",
    //       "event_name",
    //       "create_time",
    //       "event_id",
    //       "os_id",
    //       "app_id",
    //     ]; // 上面的index、nickName、name是tableData里对象的属性key值
    //     const list = this.tableData; //把要导出的数据tableData存到list
    //     const data = this.formatJson(filterVal, list);
    //     export_json_to_excel(tHeader, data, "埋点列表"); //最后一个是表名字
    //   });
    // },
    // formatJson(filterVal, jsonData) {
    //   return jsonData.map((v) => filterVal.map((j) => v[j]));
    // },
    async exportJson() {
      const res = await buryingList({
        page: 1,
        pageSize: 1000,
        id: this.idInput,
      });
      var data = JSON.stringify(res.data.list);
      //encodeURIComponent解决中文乱码
      let uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(data);
      //通过创建a标签实现
      let link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download = "埋点列表.json";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    upJson() {
      this.upDialogVisible = true;
    },
    beforeAvatarUpload(file) {
      const isTXT = file.type === "application/json";
      if (!isTXT) {
        this.$message.error("上传文件只能是 JSON 格式!");
      }
      return isTXT;
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 7, //txt
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        // point = files.name.lastIndexOf("."),//点的位置
        // suffix = files.name.substr(point),//格式文本
        // fileName = files.name.substr(0, point),//文件名
        date = Date.parse(new Date()), //时间戳
        fileNames = "/other/" + date + file.file.name;
      this.fileTxt = fileNames;
      // this.fileList = fileNames;
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          //下面是如果对返回结果再进行处理，根据项目需要
          // console.log(result);
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    async upSubmit() {
      const res = await BuryingImport({ file: this.fileTxt });
      if (res.code == 0) {
        this.$message({
          message: "导入成功",
          type: "success",
        });
        this.upDialogVisible = false;
        this.buryingList();
      }
    },
  },
  created() {
    this.buryingList();
  },
};
</script>

<style lang="less" scoped>
.BuryList {
  margin: 30px;
  height: 100%;
  .searchBox {
    display: flex;
    margin-bottom: 40px;
    position: relative;
    .el-input {
      width: 300px;
      margin-right: 10px;
    }
    .right {
      position: absolute;

      right: 0;
    }
  }
  .tac {
    margin-top: 20px;
    text-align: center;
  }
  .w300 {
    width: 100px;
  }
}
</style>